package com.shuyu.web.controller.api;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shuyu.common.constant.CacheConstants;
import com.shuyu.common.constant.Constants;
import com.shuyu.common.core.domain.Result;
import com.shuyu.common.core.domain.entity.Customer;
import com.shuyu.common.core.redis.RedisCache;
import com.shuyu.common.exception.ServiceException;
import com.shuyu.common.exception.user.CaptchaException;
import com.shuyu.common.exception.user.CaptchaExpireException;
import com.shuyu.common.utils.DesCode;
import com.shuyu.common.utils.SecurityUtils;
import com.shuyu.common.utils.StringUtils;
import com.shuyu.common.utils.VerifyCodeUtil;
import com.shuyu.common.utils.aliyun.SendSmsUtil;
import com.shuyu.common.utils.uuid.IdUtils;
import com.shuyu.domain.CustomerAssets;
import com.shuyu.domain.CustomerBehavior;
import com.shuyu.service.CustomerAssetsService;
import com.shuyu.service.CustomerBehaviorService;
import com.shuyu.service.CustomerService;
import com.shuyu.service.CustomerWxService;
import com.shuyu.vo.CustomerAddressVo;
import com.shuyu.vo.Id2MetaVerifyVo;
import com.shuyu.vo.VerifyCodeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 授权登录相关
 * 
 * @author
 */
@RestController
@RequestMapping("/api/customer")
@Api(tags = "前端-用户信息")
public class CustomerController
{
    private static final Logger log = LoggerFactory.getLogger(CustomerController.class);
    @Resource
    private CustomerAssetsService customerAssetsService;
    @Resource
    private CustomerBehaviorService customerBehaviorService;
    @Resource
    private CustomerService customerService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private CustomerWxService customerWxService;

    @GetMapping("/getInfo")
    @ApiOperation("获取用户信息")
    public Result<Customer> getInfo() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        Customer customer = customerService.getById(userId);
        return Result.success(customer);
    }

    @DeleteMapping("/delete")
    @ApiOperation("注销用户信息")
    public Result delete() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        Customer customer = customerService.getById(userId);
        customer.setDelFlag(1);
        customerWxService.removeById(customer.getThirdId());
        return Result.success(customerService.updateById(customer));
    }

    @GetMapping("/hall")
    @ApiOperation("获取用户大厅详情")
    public Result<List<CustomerAssets>> hall(){
        Long userId = SecurityUtils.getLoginUser().getUserId();
        List<CustomerAssets> list = customerAssetsService.list(new LambdaQueryWrapper<CustomerAssets>()
                .eq(CustomerAssets::getCustomerId, userId)
                .isNotNull(CustomerAssets::getPosition)
                .eq(CustomerAssets::getAssetsType,1));
        return Result.success(list);
    }
    @PutMapping("/hall/update")
    @ApiOperation("修改大厅NFT展示")
    public Result updateHall(@RequestBody CustomerAssets customerAssets){
        return Result.success(customerAssetsService.updateById(customerAssets));
    }

    @GetMapping("/bag")
    @ApiOperation("获取用户背包")
    @ApiImplicitParam(value = "资产类型 1:NFT;2:卡牌;3:MV;4:积分",name = "type",required = true)
    public Result<List<CustomerAssets>> bag(int type){
        List<CustomerAssets> list = customerAssetsService.getBag(type);
        return Result.success(list);
    }


    @PostMapping("/customerBehavior")
    @ApiOperation("记录用户行为")
    public Result customerBehavior(@RequestBody CustomerBehavior customerBehavior){
        customerBehaviorService.save(customerBehavior);
        return Result.success();
    }

    @PostMapping("/id2MetaVerify")
    @ApiOperation("实名认证")
    public Result id2MetaVerify(@RequestBody Id2MetaVerifyVo id2MetaVerify){
        customerService.id2MetaVerify(id2MetaVerify);
        return Result.success();
    }

    @GetMapping("/getSmsCode")
    @ApiOperation("获取手机验证码")
    public Result<String> getSmsCode(String mobile) throws Exception {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String msgCode = VerifyCodeUtil.getMsgCode(6);
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        Long userId = SecurityUtils.getLoginUser().getUserId();
        redisCache.setCacheObject(verifyKey, msgCode+"_"+mobile+"_"+userId, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        SendSmsUtil.send(mobile,msgCode);
        log.info("请求验证码：{},{},{}",mobile,msgCode,uuid);
        return Result.success("操作成功",uuid);
    }
    @PostMapping("/bindMobile")
    @ApiOperation("绑定手机号")
    public Result bindMobile(@RequestBody VerifyCodeVo verifyCode){
        String code = verifyCode.getCode();
        String uuid = verifyCode.getUuid();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String verify = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (verify == null)
        {
            throw new CaptchaExpireException();
        }
        String captcha = verify.split("_")[0];
        String mobile = verify.split("_")[1];
        long userIdCache = Long.parseLong(verify.split("_")[2]);
        if (!code.equals(captcha))
        {
            throw new CaptchaException();
        }
        Long userId = SecurityUtils.getLoginUser().getUserId();
        if(userIdCache != userId){
            throw new CaptchaException();
        }
        //判断号码是否已经被其他账号绑定
        int count = customerService.count(new LambdaQueryWrapper<Customer>()
                .eq(Customer::getMobile, DesCode.encrypt(mobile))
                .eq(Customer::getId, userId));
        if(count>0){
            throw new ServiceException("手机号已经被绑定",1001);
        }
        return Result.success(customerService.update(new LambdaUpdateWrapper<Customer>()
                .set(Customer::getMobile, DesCode.encrypt(mobile))
                .eq(Customer::getId,userId)));
    }

    @PostMapping("/updateAddress")
    @ApiOperation("修改收货地址")
    public Result updateAddress(@RequestBody CustomerAddressVo customerAddressVo){
        if(StringUtils.isEmpty(customerAddressVo.getProvince())
                &&StringUtils.isEmpty(customerAddressVo.getCity())
                &&StringUtils.isEmpty(customerAddressVo.getDistricts())
                &&StringUtils.isEmpty(customerAddressVo.getAddressDetail())){
            throw new ServiceException("地址信息不能为空");
        }
        Long userId = SecurityUtils.getLoginUser().getUserId();
        return Result.success(customerService.update(new LambdaUpdateWrapper<Customer>()
                .set(StringUtils.isNotEmpty(customerAddressVo.getProvince()),Customer::getProvince, DesCode.encrypt(customerAddressVo.getProvince()))
                .set(StringUtils.isNotEmpty(customerAddressVo.getCity()),Customer::getCity, DesCode.encrypt(customerAddressVo.getCity()))
                .set(StringUtils.isNotEmpty(customerAddressVo.getDistricts()),Customer::getDistricts, DesCode.encrypt(customerAddressVo.getDistricts()))
                .set(StringUtils.isNotEmpty(customerAddressVo.getAddressDetail()),Customer::getAddressDetail, DesCode.encrypt(customerAddressVo.getAddressDetail()))
                .eq(Customer::getId,userId)));
    }

}
